﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.Security;

public static class DBUserManagment
{
    private static string _connString =
        ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();

    public static DataTable GetAllUsers()
    {
        SqlDataAdapter adp = new SqlDataAdapter(@"select
		[UserName],
	    [RoleName]
        FROM [SLTestProject].[dbo].[aspnet_Users] U
	            left outer join [SLTestProject].[dbo].[aspnet_UsersInRoles] UR
		on U.UserId = UR.UserId
	            left outer join [SLTestProject].[dbo].[aspnet_Roles] R
		on R.RoleId = UR.RoleId", _connString);

        DataSet ds = new DataSet("Users");
        adp.Fill(ds, "Users");
        //ds.Tables["Users"].Columns[0].ReadOnly = true;
        return ds.Tables["Users"];
    }

    public static void RemoveUser(string username)
    {
        Membership.DeleteUser(username);
    }

    public static bool AddUser(string username, string rolename, string password="123456")
    {
        if (Membership.GetUser(username) != null)
            throw new Exception("User is already exists");
        Membership.CreateUser(username, password);
        if (Membership.ValidateUser(username,password) && Roles.RoleExists(rolename))
        {
            Roles.AddUsersToRole(username.Split(),rolename);
        }
        return true;

    }

    public static void UpdateUser(string username, string rolename)
    {
        var user = Membership.GetUser(username);
        if(user==null)
            throw new Exception("Incorrect username");
        if (Roles.GetRolesForUser(user.UserName).Length>0)
            Roles.RemoveUserFromRoles(user.UserName, Roles.GetRolesForUser(user.UserName));
        if(!string.IsNullOrEmpty(rolename))
            Roles.AddUserToRole(username,rolename);
    }
}
